package com.yftech.bletest;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "ble test";
    BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandle;
    private static final long SCAN_PERIOD = 10000;
    private static final int REQUEST_ENABLE_BT = 2;
    Map devRssiValues;

    TextView bleInfo;
    Set<BluetoothDevice> devices;
    ListView listPairedDevice;
    List arrayList;

//    //设备列表成员变量
//    private List<BluetoothDevice> mDevices;
//
//    BroadcastReceiver receiver  = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                Log.d(TAG, "onReceive: " + device.getName());
//                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//                    bleInfo.setText(device.getName());
//                    Log.d(TAG, "onReceive: 没有绑定过的蓝牙设备：" + device.getName());
//                }
//            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                Toast.makeText(getApplicationContext(), "已经搜索完毕", Toast.LENGTH_SHORT).show();
//            }
//        }
//    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bleInfo = findViewById(R.id.ble_info);
        listPairedDevice = findViewById(R.id.listBleDevice);
        arrayList = new ArrayList();
        mHandle = new Handler();
        devRssiValues = new HashMap<String, Integer>();
        //判断设备是否支持ble设备
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "设备不支持ble功能", Toast.LENGTH_SHORT).show();
            finish();
        }

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        //判断蓝牙是否打开
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "蓝牙未打开", Toast.LENGTH_SHORT).show();
            Intent enableBleIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBleIntent, REQUEST_ENABLE_BT);
        }

//        //过滤器
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
//        registerReceiver(receiver,intentFilter);
//        IntentFilter intentFilter2 = new IntentFilter();
//        intentFilter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//        registerReceiver(receiver,intentFilter2);

    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            //停止扫描设备，在预定的超时时间以后
            mHandle.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }


    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice bluetoothDevice, final int rssi, byte[] bytes) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (bluetoothDevice.getName() != null) {
                        devRssiValues.put(bluetoothDevice.getAddress(), rssi);
                        addBluetoothDevice(bluetoothDevice, rssi);
                        Log.d(TAG, "run: find device name: " + bluetoothDevice.getName() + "-----device address: " + bluetoothDevice.getAddress());
                    }

                }
            });
        }
    };

    private void addBluetoothDevice(BluetoothDevice bluetoothDevice, int rssi) {

//        arrayList.add(bluetoothDevice.getName());
//        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
//        listPairedDevice.setAdapter(adapter);


        arrayList.add(bluetoothDevice);
        //去除list中重复的蓝牙设备
        List newlist = new ArrayList(new HashSet(arrayList));
        //final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, newlist);
        DeviceAdapter adapter = new DeviceAdapter(this, newlist, devRssiValues);
        listPairedDevice.setAdapter(adapter);
    }


//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        unregisterReceiver(receiver);
//    }


//    //内部类方式，注册此广播，监听BluetoothDevice.ACTION_FOUND，以接收系统消息取得扫描结果
//    private class DeviceReceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  //这个就是所获得的蓝牙设备。
//                mDevices.add(device);
//                Log.d(TAG, "onReceive: " + device.getName());
//            }
//        }
//    }


    public void click(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_open_ble:
                openBle();
                break;
            case R.id.btn_close_ble:
                closeBle();
                break;
            case R.id.btn_get_bleinfo:
                getBleInfo();
                break;
            case R.id.btnListDevices:
                listPairedDevice();
                break;
            case R.id.btnScanDevice:
                mBluetoothAdapter.startLeScan(mLeScanCallback);

                break;
        }
    }


    private void closeBle() {
        if (mBluetoothAdapter.isEnabled()) {
            boolean close = mBluetoothAdapter.disable();
            if (close) {
                Toast.makeText(this, "蓝牙关闭成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "蓝牙关闭失败", Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(this, "蓝牙没有打开，先打开蓝牙才能关闭", Toast.LENGTH_SHORT).show();
        }
    }


    private void openBle() {
        if (!mBluetoothAdapter.isEnabled()) {
            boolean enable = mBluetoothAdapter.enable();
            if (enable) {
                Toast.makeText(this, "打开蓝牙成功", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(this, "打开蓝牙失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void getBleInfo() {
        //获取本机蓝牙名称
        String name = mBluetoothAdapter.getName();
        //获取本机蓝牙地址
        String address = mBluetoothAdapter.getAddress();
        Log.d(TAG, "bluetooth name =" + name + " address =" + address);
        bleInfo.setText("name: " + name + " address:" + address);
    }

    private void listPairedDevice() {
        //获取已配对蓝牙设备
        devices = mBluetoothAdapter.getBondedDevices();
        ArrayList arrayList = new ArrayList();

        Log.d(TAG, "bonded device size =" + devices.size());
        for (BluetoothDevice device : devices) {
            arrayList.add(device.getName());
            Log.d(TAG, "bonded device name =" + device.getName() + " address" + device.getAddress());
        }
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
        listPairedDevice.setAdapter(adapter);
    }
}
